package com.company;

public class SyncClass implements Runnable {

    private static int i = 0;

    // 同步 Class
    public static synchronized void test(){
        ++i; // 2000000
    }

    private int i2 = 0;
    // 同步对象 this
    public synchronized void test2(){
        ++ i2;  // 不同 class instance, i2 值有多个 1000000
        // 相同的 class instance, i2 值为 2000000
    }

    // 同步类属性 i
    public synchronized void test3(){
        ++i; // 1466549, 说明资源共享同步出现问题.
        // 同步的是类实例 test3() 方法, 而静态 i 是类共享变量.
        // 多线程发生了竞争.
    }

    public static void main(String[] args) throws InterruptedException {
        SyncClass obj1 = new SyncClass();
        SyncClass obj2 = new SyncClass();

        Thread thread1 = new Thread(obj1);
        Thread thread2 = new Thread(obj2);
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(i);
        // System.out.println(obj1.i2);
        // System.out.println(obj2.i2);
    }

    @Override
    public void run() {
        for(int i=0; i<1e6; ++i){
            // test()
            // test2();
            test3();
        }
        synchronized (SyncClass.class){

        }
    }
}
